﻿using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web.Caching;
using System.Web.Mvc;

namespace Gridify.Controllers
{
    public partial class GridifyController : Controller
    {
        private Cache Cache { get { return HttpContext.Cache; } }

        [HttpGet, OutputCache(Duration = 60, VaryByParam = "*")]
        public virtual ActionResult Page(int page, IEnumerable<ColumnFilter> filters, string sortBy, int sortDir, string id)
        {
            var gridData = Cache[id] as IGridData;

            if (gridData == null)
                return Json(new {failure = true}, JsonRequestBehavior.AllowGet);

            var type = gridData.GetType();
            var methodInfo = type.GetMethod("GetItems");
            var result = methodInfo.Invoke(Cache[id], new[] { (object)page, filters, sortBy, sortDir }) as ItemsInfo;
            
            Response.AddHeader("TotalPages", result.TotalPages.ToString());

            return PartialView(gridData.ViewTemplateName, result.Items);
        }

        [HttpGet]
        public ActionResult Scripts()
        {
            var stream = GetResourceStream("Gridify.Scripts.jquery.gridify.js");
            
            if (stream != null)
                return Content(new StreamReader(stream).ReadToEnd(), "application/x-javascript");

            return Content(@"alert(""Couldn't include jquery.gridify.js. Please check your configuration."");", "application/x-javascript");
        }
        
        [HttpGet]
        public ActionResult Styles()
        {
            var stream = GetResourceStream("Gridify.Content.jquery.gridify.css");

            if (stream != null)
                return Content(new StreamReader(stream).ReadToEnd(), "text/css");

            return Content("/* Couldn't find jquery.gridify.css. Please check your configuration. */", "text/css");
        }

        [HttpGet]
        public ActionResult Images(string imageUrl)
        {
            var stream = GetResourceStream("Gridify.Content.images." + imageUrl);
            
            if (stream != null)
                return new FileStreamResult(stream, "image/png");

            return Content(string.Empty, "image/png");
        }

        private static Stream GetResourceStream(string resourceName)
        {
            return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
        }
    }
}
